<template>
  <el-dialog
    class="adduser-modal"
    v-model="visible"
    :title="modal.title"
    @close="modalActions.close"
  >
    <el-form ref="formRef" :model="form" :rules="formRules" :label-width="90">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" disabled />
      </el-form-item>
      <el-form-item label="用户编号" prop="userNo">
        <el-input v-model="form.userNo" disabled />
      </el-form-item>
      <el-form-item label="电子邮箱" prop="email">
        <el-input v-model="form.email" disabled />
      </el-form-item>
      <el-form-item label="手机号码" prop="mobile">
        <el-input v-model="form.mobile" disabled />
      </el-form-item>
      <el-form-item label="用户性别" prop="sex">
        <el-radio-group v-model="form.sex" disabled>
          <el-radio :label="1">男</el-radio>
          <el-radio :label="0">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="组织机构" name="orgId" prop="orgId">
        <el-tree-select
          :render-after-expand="false"
          :data="organizations"
          :disabled="appAutoFlag == 1"
          check-strictly
          v-model="form.orgId"
          class="w-full"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="flex justify-end">
        <el-button @click="modalActions.close">取消</el-button>
        <el-button type="primary" @click="modal.submitEvent(formRef)" :loading="state.loading"
          >确定</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
  import { reactive, toRefs, watch, ref, nextTick } from 'vue';
  import { AddUser, EditUsers } from '/@/api/user';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { computed } from '@vue/reactivity';

  const appAutoFlag = ref(0);
  const { createMessage } = useMessage();
  const emit = defineEmits(['success', 'update:visible']);
  const props = defineProps({
    data: {
      type: Object,
      default: undefined,
    },
    orgList: {
      type: Array,
      default: [],
    },
    visible: {
      type: Boolean,
      default: false,
    },
  });

  const state = reactive({ loading: false });

  const modal = reactive({
    title: '新建用户',
    updateMode: false,
    submitEvent: undefined as any,
  });
  const modalActions = {
    close() {
      emit('update:visible', false);
    },
  };

  const formRef = ref();
  const form = reactive({
    username: '',
    userNo: '',
    id: '',
    sex: 0,
    orgId: '',
    email: '',
    mobile: '',
    orgUserId: '',
    innerFlag: 1,
  });
  const formRules = {
    sex: [{ required: true, message: '请选择用户性别', trigger: 'change', type: 'number' }],
    // orgId: [{ required: true, message: '请选择组织机构', trigger: 'change', type: 'number' }],
    email: [
      { required: false, message: '请输入电子邮箱', trigger: 'blur' },
      {
        pattern: /^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g,
        message: '请输入正确的邮箱',
        trigger: 'blur',
      },
    ],
    mobile: [
      { required: true, message: '请输入手机号码', trigger: 'blur' },
      {
        pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|13[0-9]|19[89])\d{8}$/,
        message: '请输入正确的手机号',
        trigger: 'blur',
      },
    ],
  };

  const { data: defaultData, orgList, visible } = toRefs(props);
  const organizations = computed(() => {
    if (defaultData?.value?.autoFlag == 1) {
      // sf同步组单独计算可选项
      return [
        {
          label: defaultData?.value.orgModel.orgName,
          value: defaultData?.value.orgModel.orgId,
        },
      ];
    } else {
      return orgList.value;
    }
  });

  const updateAction = async (formRef) => {
    formRef.validate(async (v) => {
      if (v) {
        let params = {
          userId: defaultData?.value?.id,
          sex: form.sex,
          email: form.email,
          mobile: form.mobile,
          orgId: form.orgId,
          orgUserId: form.orgUserId,
          delFlag: 0,
          lockFlag: 0,
          autoFlag: defaultData?.value?.autoFlag,
        };
        state.loading = true;
        let { code, msg } = await EditUsers(params);
        state.loading = false;
        if (code == 200) {
          createMessage({
            message: msg,
          });
          emit('update:visible', false);
          emit('success');
        }
      }
    });
  };
  const createAction = async () => {
    // let params = {
    //   sex: form.sex,
    //   email: form.email,
    //   mobile: form.mobile,
    //   orgId: form.orgId,
    //   delFlag: 0,
    //   lockFlag: 0,
    // };
    // state.loading = true;
    // let { respCode, respMsg } = await AddUser(params);
    // state.loading = false;
    // createMessage({
    //   message: respMsg,
    // });
    // if (respCode == 200) {
    //   emit('update:visible', false);
    //   emit('success');
    // }
  };
  modal.submitEvent = createAction;

  watch(visible, (nv: any) => {
    if (nv) {
      modal.updateMode = defaultData?.value?.id ? true : false;
      modal.submitEvent = modal.updateMode ? updateAction : createAction;
      modal.title = modal.updateMode ? '编辑用户' : '新建用户';
      if (modal.updateMode) {
        nextTick(async () => {
          form.username = defaultData?.value?.username;
          form.userNo = defaultData?.value?.userNo;
          form.userId = defaultData?.value?.userId;
          form.sex = +defaultData?.value?.sex;
          form.email = defaultData?.value?.email;
          form.mobile = defaultData?.value?.mobile;
          form.orgId = defaultData?.value?.orgId || '';
          form.orgUserId = defaultData?.value?.orgUserModel?.orgUserId;
          form.innerFlag = defaultData?.value?.innerFlag;
          appAutoFlag.value = defaultData?.value?.autoFlag;
          formRef.value.clearValidate();
        });
      }
    } else {
      formRef.value.resetFields();
    }
  });
</script>

<style lang="less">
  .adduser-modal {
    .ant-modal-body {
      padding: 20px;
    }
  }
</style>
